package cn.wolfcode.trip.base.admin.controller;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.domain.NewsContent;
import cn.wolfcode.trip.base.query.NewsQueryObject;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
@RequestMapping("news")
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private ServletContext ServletContext;

    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo")NewsQueryObject qo){
        model.addAttribute("result",newsService.queryForlist(qo));
        return "news/list";
    }

    /**
     * 更新或保存
     * @param news
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(MultipartFile file, News news){
        JSONResult result = new JSONResult();
        try {
            //如果有上传图片才设置
            if(file!=null&&file.getSize()>0){
                String imgUrl = UploadUtil.upload(file, ServletContext.getRealPath("/upload"));
                news.setCoverUrl(imgUrl);
            }
            if (news.getId()==null){
                newsService.save(news);
            }else {
                newsService.update(news);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 根据id查询日报内容
     */
    @RequestMapping("getNewsContentById")
    @ResponseBody
    public NewsContent getContentById(Long id){
        return newsService.getNewsContentById(id);
    }

    /**
     * 改变状态
     * @param news
     * @return
     */
    @RequestMapping("changeState")
    @ResponseBody
    public JSONResult changeState(News news){
        JSONResult result = new JSONResult();
        try {
            newsService.changeState(news);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
